
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'m8:orderRoute:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="75%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #routeList>
        <a-button class="mb-2" @click="handleRouteDataChildAdd" v-auth="'m8:orderRoute:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <BasicTable
          @register="registerRouteDataChildTable"
          @row-click="handleRouteDataChildRowClick"
        >
          <template #sortUp="{ record }">
            <a @click="clickUp(record)" style="padding: 8px">
              <Icon icon="ant-design:arrow-up-outlined" size="18" color="#efbd47" />
            </a>
            <a @click="clickDown(record)">
              <Icon icon="ant-design:arrow-down-outlined" size="18" color="#efbd47" />
            </a>
          </template>
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasM8OrderRouteForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { M8OrderRoute, m8OrderRouteSave, m8OrderRouteForm } from '/@/api/bas/m8OrderRoute';
  import { operTreeData } from '/@/api/bas/route/route';
import { log } from 'node:console';

  const emit = defineEmits(['success', 'register', 'closeModal', 'openDrawer']);

  const { t } = useI18n('bas.m8OrderRoute');
  const { showMessage } = useMessage();
  const record = ref<M8OrderRoute>({} as M8OrderRoute);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增工艺列表') : t('编辑工艺列表'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('订单ID'),
      field: 'order.id',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      show: false,
    },
    {
      label: t('图纸ID'),
      field: 'id',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      show: false,
    },
    {
      label: t(''),
      field: 'routeList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'routeList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await m8OrderRouteForm(data);
    record.value = (res.m8OrderPic || {}) as M8OrderRoute;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setRouteDataChildTableData(res);
    setDrawerProps({ loading: false });
  });

  const [registerRouteDataChildTable, RouteDataChildTable] = useTable({
    actionColumn: {
      width: 80,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRouteDataChildDelete.bind(this, record),
          },
          auth: 'm8:orderRoute:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showIndexColumn: true, //是否显示序列号
  });

  async function setRouteDataChildTableData(_res: Recordable) {
    RouteDataChildTable.setColumns([
      {
        title: t('上移 / 下移'),
        slot: 'sortUp',
        width: 90,
      },
      {
        title: t('工序'),
        dataIndex: 'oper.operCode',
        dataLabel: 'oper.operName',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: operTreeData,
          params: {
            onlyParent: 1,
            bsx: 0,
          },
          canSelectParent: false,
        },
        editRule: true,
      },
      {
        title: t('加工时长'),
        dataIndex: 'jgtime',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('调试时长'),
        dataIndex: 'tstime',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      // {
      //   title: t('单价'),
      //   dataIndex: 'fprice',
      //   width: 80,
      //   align: 'center',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editRule: false,
      // },
      {
        title: t('班次数'),
        dataIndex: 'teamQty',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('表面处理'),
        dataIndex: 'bmcl',
        width: 180,
        align: 'left',
        dictType: 'm8_outer_route',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'm8_outer_route',
          mode: 'multiple',
          allowClear: true,
        },
        editRule: false,
        // editRule: (text: any, record: Recordable) => {
        //   return new Promise((resolve, reject) => {
        //     if (record.oper.operCode == 'WX') {
        //       reject('请选择表面处理');
        //     } else {
        //       resolve();
        //     }
        //   });
        // },
      },
      {
        title: t('加工备注'),
        dataIndex: 'remarks',
        width: 180,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
      },
    ]);
    if (record.value.routeList) {
      record.value.routeList.forEach((item, index) => {
        if (!item.id) {
          item.id = index + 1;
        }
      });
    }
    RouteDataChildTable.setTableData(record.value.routeList || []);
  }

  function handleRouteDataChildAdd() {
    RouteDataChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  // 删除新增行
  function handleRouteDataChildDelete(record: Recordable) {
    RouteDataChildTable.deleteTableDataRecord(record);
  }

  function clickUp(record) {
    // 上移
    let arr = RouteDataChildTable.getDataSource();

    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }

    if (index === 0) {
      return false;
    }

    arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    RouteDataChildTable.setTableData(arr || []);
  }

  // 下移
  function clickDown(record) {
    let arr = RouteDataChildTable.getDataSource();
    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }
    if (index === arr.length - 1) {
      return false;
    }
    arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    RouteDataChildTable.setTableData(arr || []);
  }

  //获取表格数据
  async function getRouteDataChildList() {
    let routeDataChildListValid = true;
    let routeDataChildList: Recordable[] = [];
    for (const record of RouteDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        routeDataChildListValid = false;
      }
      routeDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of RouteDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      routeDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!routeDataChildListValid) {
      throw { errorFields: [{ name: ['routeDataChildList'] }] };
    }
    return routeDataChildList;
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.routeList = await getRouteDataChildList();
      let flag = true;
      RouteDataChildTable.getDataSource().forEach((item) => {
        if (item.oper.bout == '1'  && !item.bmcl) {
          flag = false;
        }
      });
      
      if (!flag) {
        showMessage(t('工序为外协时表面处理必填。'));
      } else {
        const res = await m8OrderRouteSave(params, data);
        setDrawerProps({ confirmLoading: false });
        showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
      }
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  function handleRouteDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }
</script>
